<?php

namespace app\common\model\common;

use app\common\controller\Frontend;
use app\common\controller\SysBackend;
use app\common\facade\Token;
use app\common\library\token\TokenExpirationException;
use app\common\model\banxi\organization\OrganizationUser as OrganizationUser;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\sys\SysUser;
use app\common\model\banxi\trainer\Trainer;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Model;

class BaseModel extends Model
{

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    //-----------------------------------------------------------------------------------
    //｜                                   方法                                       ｜
    //-----------------------------------------------------------------------------------
    public static function dealUser()
    {
        $dealUser = '';
        $platform = request()->header('platform', 'sys_user');
        try {
            switch ($platform) {
                case 'sys_user':
                    $token = get_auth_token(SysBackend::getTokenName());
                    $modelClass = new SysUser();
                    $field = 'userName';
                    $cachePrefix = 'token_sys_user';
                    break;
                case 'client':
                    $token = get_auth_token(Frontend::getPlatformAuth('client')['token_name']);
                    $modelClass = new Student();
                    $field = 'account';
                    $cachePrefix = 'token_client';
                    break;
                case 'teacher':
                    $token = get_auth_token(Frontend::getPlatformAuth('teacher')['token_name']);
                    $modelClass = new Trainer();
                    $field = 'account';
                    $cachePrefix = 'token_teacher';
                    break;
                case 'organization':
                    $token = get_auth_token(Frontend::getPlatformAuth('organization')['token_name']);
                    $modelClass = new OrganizationUser();
                    $field = 'account';
                    $cachePrefix = 'token_organization';
                    break;
                default:
                    return $dealUser;
            }

            // 统一处理token验证
            if (!$token) {
                return $dealUser;
            }

            $tokenData = Token::get($token);
            if (!$tokenData) {
                return $dealUser;
            }
            Token::tokenExpirationCheck($tokenData);
            $userId = intval($tokenData['user_id']);

            $key = "{$cachePrefix}_{$token}";
            if (Cache::has($key)) {
                $dealUser = Cache::get($key);
            } else {
                // 使用统一的方式获取用户信息
                $dealUser = $modelClass->where(['id' => $userId])
                    ->cache($key, 60)
                    ->value($field);
            }
        } catch (Exception|PDOException|ValidateException $e) {
            // 可以添加日志记录
            return $dealUser;
        }catch(TokenExpirationException $e){
            return $dealUser;
        }
        return $dealUser;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型事件                                       ｜
    //-----------------------------------------------------------------------------------

    public static function onBeforeInsert(Model $model)
    {
        $name = self::dealUser();
        $model['createBy'] = $name;
        $model['updateBy'] = $name;
        return $model;
    }

    public static function onBeforeUpdate(Model $model)
    {
        $name = self::dealUser();
        $model['updateBy'] = $name;
        return $model;
    }

    public static function onBeforeDelete(Model $model)
    {
        $name = self::dealUser();
        $model['updateBy'] = $name;
        return $model;
    }

}